package ru.spbau.design.snmp.android.viewer.provider;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import ru.spbau.design.snmp.android.viewer.model.ModelException;
import ru.spbau.design.snmp.android.viewer.model.NetworkSnapshot;
import ru.spbau.design.snmp.android.viewer.model.NetworkSnapshotXMLParser;

import android.content.Context;
import android.content.res.AssetManager;

public final class NetworkSnapshotProviderFile implements INetworkSnapshotProvider {

	public NetworkSnapshotProviderFile(String fileName, Context context) {
		this.fileName = fileName;
		this.context = context;
	}

	@Override
	public NetworkSnapshot getNetworkSnapshot() throws ModelException {
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(getInputStream());
			NetworkSnapshotXMLParser snapshotParser = 
					new NetworkSnapshotXMLParser();
			NetworkSnapshot result = snapshotParser.parseXML(doc);
			return result;

		} catch (Exception e) {
			throw new ModelException(e);
		}
	}

	private InputStream getInputStream() throws Exception {
		AssetManager am = context.getAssets();
		InputStream is = am.open(fileName);
		return is;
	}

	private final String fileName;
	private final Context context;
}
